/*
 * Copyright (c) www.bugull.com
 */

package com.bugull.farm.app.server.processor;

import org.apache.logging.log4j.*;

import com.bugull.farm.app.server.cache.AppCache;
import com.bugull.farm.core.cache.PropertiesCache;
import com.bugull.farm.core.frame.structure.Frame;
import com.bugull.farm.core.handler.Processor;
import com.bugull.farm.core.store.User;
import com.bugull.mongo.BuguDao;
import com.bugull.mongo.cache.DaoCache;

import io.netty.channel.ChannelHandlerContext;

/**
 * For command: CMD_APP_JOIN, app join and return the aes key
 * 
 * @author Frank Wen(xbwen@hotmail.com)
 */
public class AppJoinProcessor implements Processor {
    
    private final static Logger logger = LogManager.getLogger(AppJoinProcessor.class);
    private PropertiesCache props = PropertiesCache.getInstance();

    @Override
    public void process(ChannelHandlerContext ctx, Frame frame) throws Exception{
		//auth the app joinCode
		String joinCode = frame.getHexStr("joinCode");
		if (!joinCode.equals(props.get("app.join.code"))) {
			ctx.close();
			return;
		}
		String username = frame.getASCIIStr("username");
		String password = frame.getASCIIStr("password");
		BuguDao<User> userDao = DaoCache.getInstance().get(User.class);
		User user = userDao.findOne("username",username);
		if(user == null || !password.equals(user.getPassword())){
			ctx.close();
			return;
		}
		//接入成功，回复APP
		ctx.writeAndFlush(frame.getFastResponse());
		//接入成功后标记channel信息
		AppCache.getInstance().addJoin(username, ctx.channel());
	}
}
